package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @Author: KuangJieWen
 * @Date: 2018/3/8 10:01
 * @Description:请在此添加描述
 */
public class NIOClient {
    private Selector selector;

    public void init() throws IOException {
        selector=Selector.open();
        SocketChannel socketChannel=SocketChannel.open();
        socketChannel.configureBlocking(false);//要设置成非阻塞的，否则会报错
        socketChannel.connect(new InetSocketAddress("127.0.0.1",9090));
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
    }

    public String read() throws IOException {
        String msg;
        selector.select();
        Iterator<SelectionKey> iterator=selector.selectedKeys().iterator();
        while (iterator.hasNext()){
            SelectionKey selectionKey=iterator.next();
            if(selectionKey.isConnectable()){
                System.out.println("准备读出信息");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                SocketChannel socketChannel= (SocketChannel) selectionKey.channel();
                if(socketChannel.isConnectionPending()){
                    socketChannel.finishConnect();
                }
                socketChannel.configureBlocking(false);
                ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
                socketChannel.read(byteBuffer);
                byteBuffer.flip();
                System.out.println(byteBuffer.limit());
                byte []b=new byte[byteBuffer.limit()];
                byteBuffer.get(b);
                System.out.println(b.length);
                msg=new String(byteBuffer.array(),"UTF-8");
                return msg;
            }
        }
        return "暂无消息";
    }


    public static void main(String[] args) throws IOException {
        NIOClient client=new NIOClient();
        client.init();
        System.out.println("msg:"+client.read());
        ThreadLocal local=new ThreadLocal();
        local.set("fuck");
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {

            }
        });
    }
}
